package com.log;

import org.apache.commons.math3.analysis.solvers.BrentSolver;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.exception.TooManyEvaluationsException;

public class IRRCalculation {
    public static void main(String[] args) {
        // 每月缴费
        double monthlyPayment = 3092;

        // 缴费期（年）
        int years = 5;

        // 月数
        int months = years * 12;

        // 每月利息
        double monthlyInterest = 0.03;

        // 计算每月现金流
        double[] cashFlows = new double[months + 1];
        for (int i = 0; i < months; i++) {
            cashFlows[i] = -monthlyPayment;
        }

        // 计算最终收益
        double totalPayment = 0;
        for (int i = 0; i < months; i++) {
            totalPayment += monthlyPayment * Math.pow(1 + monthlyInterest, months - i);
        }
        cashFlows[months] = totalPayment;

        // 使用BrentSolver来计算内部收益率（IRR）
        BrentSolver solver = new BrentSolver();
        UnivariateFunction irrFunction = rate -> {
            double npv = 0;
            for (int t = 0; t <= months; t++) {
                npv += cashFlows[t] / Math.pow(1 + rate, t);
            }
            return npv;
        };

        // 扩大搜索区间
        double lowerBound = -0.99;
        double upperBound = 1.0;

        try {
            // 估计内部收益率
            double irr = solver.solve(10000, irrFunction, lowerBound, upperBound);

            // 转换为年利率
            double annualIRR = Math.pow(1 + irr, 12) - 1;

            // 输出实际年利率
            System.out.printf("实际年利率: %.6f%%%n", annualIRR * 100);
        } catch (TooManyEvaluationsException e) {
            System.err.println("IRR calculation did not converge.");
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }
}
